package bll

import (
	"context"
	"gorm.io/gorm/utils"
	"manager/event"
	"manager/model"
	"manager/store/redis"
	"time"
)

const (
	RedisKeyBikeType = "bike_type"
)

var CacheBikeType = &cacheBikeType{}

// cacheBikeType 缓存车辆类型
type cacheBikeType struct {
}

func (c *cacheBikeType) init() func() {
	return func() {}
}

func (c *cacheBikeType) onEvent(data *event.Data) {}

// GetBikeTypeId 根据车辆Id获取车辆类型
func (c *cacheBikeType) GetBikeTypeId(typeId int64) (info *model.EbikeTypeInfo, err error) {
	// 从缓存中获取车辆类型
	info = &model.EbikeTypeInfo{}
	redis.KV.GetValue(context.Background(), RedisKeyBikeType, utils.ToString(typeId), info)
	if info.ID > 0 {
		return
	}

	// 从数据库中获取车辆类型
	info, err = EbikeType.Info(context.Background(), &model.EbikeTypeBaseRequest{ID: typeId})
	if err != nil || info == nil {
		return
	}

	// 设置缓存
	redis.KV.AddValueWithExpireTime(context.Background(), RedisKeyBikeType, utils.ToString(typeId), info, time.Second*600)
	return
}

// DeleteCache 删除缓存
func (c *cacheBikeType) DeleteCache(bikeId int64) (err error) {
	return redis.KV.DelValue(context.Background(), RedisKeyBikeType, utils.ToString(bikeId))
}
